package cn.com.netedge.iot.frontend.biz;

import cn.com.netedge.iot.common.constants.CacheKeyConstants;
import cn.com.netedge.iot.common.constants.Globals;
import cn.com.netedge.iot.common.utils.*;
import cn.com.netedge.iot.frontend.biz.config.BpConfig;
import cn.com.netedge.iot.frontend.biz.utils.JmsMsgUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.scheduling.annotation.EnableScheduling;

import java.util.Date;

@SpringBootApplication(exclude = {RedisAutoConfiguration.class})
@ComponentScan(basePackages = {"cn.com.netedge.iot.fe.biz","cn.com.netedge.iot.protocol","cn.com.netedge.iot.common.utils"})
@EnableScheduling
public class FeBizApplication {
    private static Logger logger = LoggerFactory.getLogger(FeBizApplication.class);

    public static void main(String[] args) {
        logger.debug("Starting application with args: {}", args);
        ApplicationContext context = SpringApplication.run(FeBizApplication.class, args);
        BpConfig.appContext = context;

        initApp();
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            logger.debug("Detected shutdown, cleaning up...");
            ChronicleQueueUtil.close();
        }));

    }

    public static void initApp() {
        FrontEndUtil frontEndUtil = BpConfig.appContext.getBean(FrontEndUtil.class);
        BpConfig.setMachineName(CacheKeyConstants.KEY_FRONTEND_BIZ_MACHINE + frontEndUtil.getMachineNo());
        Date now = new Date();
        RedisUtil.hset(CacheKeyConstants.KEY_FRONTEND_BIZ_MACHINE + "machine_map", BpConfig.getMachineName(), DateUtil.DateToLongStr(now));

        JmsMsgUtil jmsMsgUtil = BpConfig.appContext.getBean(JmsMsgUtil.class);
        JmsMsgUtil.setAppName(Globals.APP_FRONTEND_BIZ);
        jmsMsgUtil.subscribeQueues();

        String configPath = System.getProperty("configPath");
        logger.info("configPath:{}", configPath);
        if (StringUtil.isEmpty(configPath)) {//云平台
            logger.info("进入 云平台模式");

            return;
        }
        logger.info("进入 本地版模式");
        BpConfig.setLocalMode(true);
    }

}
